package horario.vista;

import horario.controlador.ControladorEntrada;
import horario.controlador.ControladorUsuario;
import horario.recursos.beans.BeanFechaHora;
import horario.recursos.beans.BeanUsuario;
import horario.recursos.utiles.LE;
import horario.recursos.utiles.SntpClient;
import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;

/**
 *
 * @author Metis Gaia 2010-02
 */
public class horario extends javax.swing.JFrame {

    ControladorUsuario controladorUsuario = new ControladorUsuario();
    ControladorEntrada controladorEntrada = new ControladorEntrada();
    ArrayList<BeanUsuario> listaBean = null;
    SntpClient sntClient = null;
    

    public horario() {
        try {
            listaBean = controladorUsuario.listarUsuarios();
        } catch (Exception ex) {
            Logger.getLogger(horario.class.getName()).log(Level.SEVERE, null, ex);
        }
        initComponents();
        //btnJustificarTardanza.setEnabled(false);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jInternalFrame1 = new javax.swing.JInternalFrame();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        btnJustificarTardanza = new javax.swing.JButton();
        btnEntrada = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        cbxUsuario = new javax.swing.JComboBox();
        txtPassword = new javax.swing.JPasswordField();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jmiRegistrarGasto = new javax.swing.JMenuItem();
        jmiMantCentroCostos = new javax.swing.JMenuItem();

        jInternalFrame1.setVisible(true);

        javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
        jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
        jInternalFrame1Layout.setHorizontalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jInternalFrame1Layout.setVerticalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Metis Gaia");
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Modulo para registrar horario");

        btnJustificarTardanza.setText("JUSTIFICAR TARDANZA");
        btnJustificarTardanza.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnJustificarTardanzaActionPerformed(evt);
            }
        });

        btnEntrada.setText("ENTRADA");
        btnEntrada.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEntradaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(btnEntrada)
                .addGap(28, 28, 28)
                .addComponent(btnJustificarTardanza, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(btnJustificarTardanza, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(btnEntrada, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
        );

        try {
            ArrayList<String> lista = new ArrayList<String>();
            lista.add("[SELECCIONE]");
            for (BeanUsuario x : listaBean){
                lista.add(x.getUsuario());
            }

            String [] listaUsuarios = new String[lista.size()];
            lista.toArray(listaUsuarios);
            cbxUsuario.setModel(new DefaultComboBoxModel(listaUsuarios) );
        } catch (Exception ex) {
            Logger.getLogger(horario.class.getName()).log(Level.SEVERE, null, ex);
        }

        jLabel3.setText("Password:");

        jLabel2.setText("Usuario:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(14, 14, 14)
                        .addComponent(cbxUsuario, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap(31, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cbxUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        jMenu1.setText("GASTOS");

        jmiRegistrarGasto.setText("Registrar gasto");
        jmiRegistrarGasto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmiRegistrarGastoActionPerformed(evt);
            }
        });
        jMenu1.add(jmiRegistrarGasto);

        jmiMantCentroCostos.setText("Mantenimiento de Centro de Costos");
        jmiMantCentroCostos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmiMantCentroCostosActionPerformed(evt);
            }
        });
        jMenu1.add(jmiMantCentroCostos);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 313, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(44, 44, 44)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(46, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(15, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnEntradaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEntradaActionPerformed
        try {
            // TODO add your handling code here:
            boolean valido = false;
            boolean insertado = false;
            boolean entrada_marcada = false;
            boolean salida_marcada = false;

            if (cbxUsuario.getSelectedIndex() != 0) {
                valido = controladorUsuario.validarUsuario(listaBean, cbxUsuario.getSelectedItem().toString(), String.valueOf(txtPassword.getPassword()));
                if (valido == true) {
                    System.out.println("usuario validado");
                    //verificar que no se haya marcado ya la hora de entrada para el presente día
                    java.util.Date utilDate = new java.util.Date();
                    Date fecha_hoy = new Date(utilDate.getTime());
                    Time hora_actual = new Time(utilDate.getTime());
                    System.out.println("fecha "+fecha_hoy);
                    System.out.println("hora "+hora_actual);
                    sntClient = new SntpClient();
                    Date fecha_hoy_2 = sntClient.obtenerFechaActual();
                    System.out.println("fecha 2 "+fecha_hoy_2);
                    Time hora_actual_2 = sntClient.obtenerHoraActual();
                    System.out.println("hora 2 "+hora_actual_2);
                    int id = controladorUsuario.obtenerId(listaBean, cbxUsuario.getSelectedItem().toString());
                    entrada_marcada = controladorUsuario.existeEntrada(id, fecha_hoy);

                    if (!entrada_marcada) {
                        //poner true como indicadorES porqeu es una entrada la que se registrara
                        insertado = controladorEntrada.insertarFechaHora(true, id, fecha_hoy, hora_actual, false, 1, null);
                        if (insertado) {
                            LE.mostrarInformacion("Se registró la hora de entrada");
                        } else {
                            LE.mostrarInformacion("No se pudo registrar la hora de entrada");
                        }

                    } else {
                        LE.mostrarInformacion("Este usuario ya tiene registrada la hora de entrada para el día de hoy");
                    }

                } else {
                    LE.mostrarError("Contraseña inválida");
                }
            } else {
                LE.mostrarError("Seleccione un usuario por favor");
            }
        } catch (Exception ex) {
            Logger.getLogger(horario.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_btnEntradaActionPerformed

    private void btnJustificarTardanzaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnJustificarTardanzaActionPerformed
        // TODO add your handling code here:
        try {
            // TODO add your handling code here:
            boolean valido = false;
            boolean insertado = false;
            boolean entrada_marcada = false;
            boolean salida_marcada = false;

            if (cbxUsuario.getSelectedIndex() != 0) {
                valido = controladorUsuario.validarUsuario(listaBean, cbxUsuario.getSelectedItem().toString(), String.valueOf(txtPassword.getPassword()));
                if (valido == true) {
                    System.out.println("usuario validado");
                    //verificar que no se haya marcado ya la hora de entrada para el presente día
                    java.util.Date utilDate = new java.util.Date();
                    Date fecha_hoy = new Date(utilDate.getTime());
                    Time hora_actual = new Time(utilDate.getTime());
                    int id = controladorUsuario.obtenerId(listaBean, cbxUsuario.getSelectedItem().toString());
                    //verifico si ya marco entrada anteriormente en esta fecha
                    entrada_marcada = controladorUsuario.existeEntrada(id, fecha_hoy);

                    if (!entrada_marcada) {
                        BeanFechaHora beanFechaHora = new BeanFechaHora(id, cbxUsuario.getSelectedItem().toString(), fecha_hoy, hora_actual);
                        new justifica(null, true, beanFechaHora).setVisible(true);

                    } else {
                        LE.mostrarInformacion("Este usuario ya tiene registrada la hora de entrada para el día de hoy");
                        if (LE.mostrarPreguntaOpcion2("Desea Ingresar Gastos")==0) {
                            new gastos(this, true, id).setVisible(true);
                        } else {
                            cbxUsuario.setSelectedIndex(0);
                            txtPassword.setText("");
                            
                        }
                    }

                } else {
                    LE.mostrarError("Contraseña inválida");
                    btnEntrada.transferFocus();
                    txtPassword.requestFocus();
                }
            } else {
                LE.mostrarError("Seleccione un usuario por favor");
            }
        } catch (Exception ex) {
            Logger.getLogger(horario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnJustificarTardanzaActionPerformed

private void jmiRegistrarGastoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiRegistrarGastoActionPerformed
        try {
            // TODO add your handling code here:
                new gastos(this, true, 11).setVisible(true);
        } catch (Exception ex) {
            Logger.getLogger(horario.class.getName()).log(Level.SEVERE, null, ex);
        }
    
}//GEN-LAST:event_jmiRegistrarGastoActionPerformed

private void jmiMantCentroCostosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiMantCentroCostosActionPerformed
        // TODO add your handling code here:
        new centroCostos(this, true).setVisible(true);
    
}//GEN-LAST:event_jmiMantCentroCostosActionPerformed

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new horario().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEntrada;
    private javax.swing.JButton btnJustificarTardanza;
    private javax.swing.JComboBox cbxUsuario;
    private javax.swing.JInternalFrame jInternalFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JMenuItem jmiMantCentroCostos;
    private javax.swing.JMenuItem jmiRegistrarGasto;
    private javax.swing.JPasswordField txtPassword;
    // End of variables declaration//GEN-END:variables
}
